﻿using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HRM.Model;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using HRM.Helper;
using System.Windows;

namespace HRM.ViewModel
{
    public class ProjectViewModel : ViewModelBase
    {
        private readonly IProjectService _projectService;
        private NguoiSuDung _user;
        private List<DuAn> _projects = new List<DuAn>();

        /// <summary>
        /// Danh sách dự án để binding ra giao diện
        /// </summary>
        public List<DuAn> Projects
        {
            get
            { return _projects; }
            set
            {
                if (_projects != value)
                {
                    _projects = value;
                    RaisePropertyChanged("Projects");
                }
            }
        }

        private int _totalItems = 0;

        public int TotalItems
        {
            get { return _totalItems; }
            set
            {
                if (_totalItems != value)
                {
                    _totalItems = value;
                    RaisePropertyChanged("TotalItems");
                }
            }
        }

        #region Property Search

        private bool _searchByID = true;

        /// <summary>
        /// Tìm kiếm theo Id
        /// </summary>
        public bool SearchByID
        {
            get { return _searchByID; }
            set
            {
                if (_searchByID != value)
                {
                    _searchByID = value;
                    RaisePropertyChanged("SearchByID");
                }
            }
        }

        private bool _searchByProjectName = false;

        /// <summary>
        /// Tìm kiếm theo tên dự án
        /// </summary>
        public bool SearchByProjectName
        {
            get { return _searchByProjectName; }
            set
            {
                if (_searchByProjectName != value)
                {
                    _searchByProjectName = value;
                    RaisePropertyChanged("SearchByProjectName");
                }
            }
        }

        private string _searchInput = string.Empty;

        /// <summary>
        /// Chuỗi tìm kiếm
        /// </summary>
        public string SearchInput
        {
            get { return _searchInput; }
            set
            {
                if (_searchInput != value)
                {
                    _searchInput = value;
                    RaisePropertyChanged("SearchInput");
                }
            }
        }

        #endregion

        #region Property Update or Add Item

        private bool _addmode = true;

        public bool AddMode
        {
            get { return _addmode; }
            set
            {
                if (_addmode != value)
                {
                    _addmode = value;
                    RaisePropertyChanged("AddMode");
                }
            }
        }

        private bool _updateMode = false;

        public bool UpdateMode
        {
            get { return _updateMode; }
            set
            {
                if (_updateMode != value)
                {
                    _updateMode = value;
                    RaisePropertyChanged("UpdateMode");
                }
            }
        }

        private string _projectIDInput = string.Empty;

        public string ProjectIDInput
        {
            get { return _projectIDInput; }
            set
            {
                if (_projectIDInput != value)
                {
                    _projectIDInput = value;
                    RaisePropertyChanged("ProjectIDInput");
                }
            }
        }

        private string _projectNameInput = string.Empty;

        public string ProjectNameInput
        {
            get { return _projectNameInput; }
            set
            {
                if (_projectNameInput != value)
                {
                    _projectNameInput = value;
                    RaisePropertyChanged("ProjectNameInput");
                }
            }
        }

        #endregion

        #region Property Paging DataGrid

        private int _pageIndex = 1;

        public int PageIndex
        {
            get { return _pageIndex; }
            set
            {
                if (_pageIndex != value)
                {
                    _pageIndex = value;
                    RaisePropertyChanged("PageIndex");
                }
            }
        }

        private int _numberOfPages = 1;

        public int NumberOfPages
        {
            get { return _numberOfPages; }
            set
            {
                if (_numberOfPages != value)
                {
                    _numberOfPages = value;
                    RaisePropertyChanged("NumberOfPages");
                }
            }
        }

        private int _pageSize = 10;

        public int PageSize
        {
            get { return _pageSize; }
            set
            {
                if (_pageSize != value)
                {
                    _pageSize = value;
                    RaisePropertyChanged("PageSize");
                }
            }
        }

        #endregion

        #region Commands

        public RelayCommand SearchCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    if (_searchByID)
                    {
                        Projects = _projectService.SearchByProjectID(SearchInput);
                    }
                    else if (_searchByProjectName)
                    {
                        Projects = _projectService.SearchByProjectName(SearchInput);
                    }
                    Messenger.Default.Send(new StatusMessage("Kết quả tìm kiếm đã được cập nhât", 3000, StatusType.Done));
                });
            }
        }

        public RelayCommand<bool> CheckAllCommand
        {
            get
            {
                return new RelayCommand<bool>((obj) =>
                {
                    if (obj)
                    {
                        foreach (var item in Projects)
                        {
                            item.IsChecked = true;
                        }
                    }
                    else
                    {
                        foreach (var item in Projects)
                        {
                            item.IsChecked = false;
                        }
                    }
                });
            }
        }

        public RelayCommand<DuAn> DataGridSelectionCommand
        {
            get
            {
                return new RelayCommand<DuAn>((obj) =>
                {
                    if (obj == null) return;

                    UpdateMode = true;
                    ProjectIDInput = obj.MaDuAn;
                    ProjectNameInput = obj.TenDuAn;
                });
            }
        }

        public RelayCommand SaveCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    if (ProjectIDInput != "" && ProjectNameInput != "")
                    {
                        if (UpdateMode)
                        {
                            if (_projectService.Update(ProjectIDInput, ProjectNameInput))
                            {
                                Refresh();
                                Messenger.Default.Send(new StatusMessage("Sửa thành công", 3000, StatusType.Done));
                            }
                            else
                            {
                                Messenger.Default.Send(new StatusMessage("Đã xảy ra lỗi", 3000, StatusType.Error));
                            }
                        }
                        else if (AddMode)
                        {
                            if (_projectService.Add(ProjectIDInput, ProjectNameInput))
                            {
                                Refresh();
                                Messenger.Default.Send(new StatusMessage("Đã thêm thành công", 3000, StatusType.Done));
                            }
                            else
                            {
                                Messenger.Default.Send(new StatusMessage("Mã dự án đã tồn tại", 3000, StatusType.Error));
                            }
                        }
                    }
                }, () => _user.GetPermisstion);
            }
        }

        public RelayCommand NextPageCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    if (PageIndex < NumberOfPages)
                    {
                        PageIndex++;
                        Projects = _projectService.GetPaging(PageIndex, PageSize);
                    }
                });
            }
        }

        public RelayCommand PreviosPageCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    if (PageIndex > 1)
                    {
                        PageIndex--;
                        Projects = _projectService.GetPaging(PageIndex, PageSize);
                    }
                });
            }
        }

        public RelayCommand LastPageCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    PageIndex = NumberOfPages;
                    Projects = _projectService.GetPaging(NumberOfPages, PageSize);
                });
            }
        }

        public RelayCommand FirstPageCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    PageIndex = 1;
                    Projects = _projectService.GetPaging(1, PageSize);
                });
            }
        }

        public RelayCommand<DuAn> DeleteCommand
        {
            get
            {
                return new RelayCommand<DuAn>((da) =>
                {
                    if (da == null) return;
                    if (_projectService.Delete(da))
                    {
                        Refresh();
                        Messenger.Default.Send(new StatusMessage("Xóa thành công.", 3000, StatusType.Done));
                    }
                }, (da) => _user.GetPermisstion);
            }
        }

        public RelayCommand DeleteListCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    var list = Projects.FindAll(x => x.IsChecked == true);
                    if (MessageBox.Show(string.Format("Xóa {0} bản ghi?", list.Count), "Xác nhận", MessageBoxButton.OKCancel, MessageBoxImage.Warning, MessageBoxResult.Cancel) == MessageBoxResult.OK)
                    {
                        if (_projectService.DeleteList(list))
                        {
                            Refresh();
                            Messenger.Default.Send(new StatusMessage(list.Count.ToString() + " bản ghi đã được xóa", 3000, StatusType.Done));
                        }
                        else
                        {
                            Messenger.Default.Send(new StatusMessage("Đã xảy ra lỗi khi truy cập CSDL", 3000, StatusType.Error));
                        }
                    }
                }, () => _user.GetPermisstion);
            }
        }

        public RelayCommand RefreshCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    PageIndex = 1;
                    Refresh();
                });
            }
        }

        #endregion

        public void Refresh()
        {
            NumberOfPages = _projectService.GetNumberOfPages(PageSize);
            Projects = _projectService.GetPaging(PageIndex, PageSize);
            TotalItems = _projectService.GetByAll().Count;
        }


        /// <summary>
        /// Khởi tạo ViewModel với các service tương ứng
        /// </summary>
        /// <param name="projectService">interface service</param>
        public ProjectViewModel(IProjectService projectService)
        {
            _projectService = projectService;
            _user = SimpleIoc.Default.GetInstance<NguoiSuDung>();
            Refresh();
        }
    }
}
